from monkey import monkey_open as open
from common import data_from_image, image_from_data
from PIL import Image, ImageFilter

# Sharpens an image. 
# The image argument is either the data of an image file, in which case 
# the isfile argument should be False [default], or it is an id of a 
# file stored in the surrogates storage, in which case isfile should 
# be True.
def perform(image, isfile=False):
    # Load the image file.
    if isfile:
        imgfile = open(image, 'r')
        img = Image.open(imgfile)
        close(imgfile)
    else:
        img = image_from_data(image)
        
    # Sharpen the image.
    img = img.filter(ImageFilter.SHARPEN)

    # Return or write the sharpened image.
    if isfile:
        img.save('storage/' + image, 'jpeg')
        return 0
    else:
        return data_from_image(img)